package com.wosiliujing.learning.component;

import cn.hutool.core.util.ReUtil;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.wosiliujing.learning.annotation.Ignore;
import com.wosiliujing.learning.annotation.Inner;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;

/***
 * 资源服务器对外直接暴露URL处理（Inner 注解url + 配置文件配置的ignore-urls）
 * @author 刘靖
 * @date 2019/9/18 10:18
 */
@Slf4j
@Configuration
@ConditionalOnExpression("!'${security.oauth2.client.ignore-urls}'.isEmpty()")
@ConfigurationProperties(prefix = "security.oauth2.client")
@AllArgsConstructor
public class PermitAllUrlProperties implements InitializingBean {

    private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}");
    private final WebApplicationContext applicationContext;

    @Getter
    @Setter
    private List<String> ignoreUrls = new ArrayList<>();


    @Override
    public void afterPropertiesSet() {
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        map.keySet().forEach(info -> {
            HandlerMethod handlerMethod = map.get(info);
            //方法上的进行处理 内部接口与不鉴权接口过滤
            Inner innerMethod = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), Inner.class);
            Optional.ofNullable(innerMethod).ifPresent(inner ->
                info.getPatternsCondition().getPatterns()
                        .forEach(url ->  ignoreUrls.add(ReUtil.replaceAll(url, PATTERN, StringPool.ASTERISK)))
            );
            Ignore ingnoreMethod = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), Ignore.class);
            Optional.ofNullable(ingnoreMethod).ifPresent(inner ->
                    info.getPatternsCondition().getPatterns()
                            .forEach(url ->  ignoreUrls.add(ReUtil.replaceAll(url, PATTERN, StringPool.ASTERISK)))
            );
        });

    }
}
